package org.fight.landowner.remoting;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @Author wangxuehao02
 * @Date 2024/2/7 11:13 AM
 * @Description
 * todo 是否需要继承 Future 接口？与其他 Future 相比功能上是否有欠缺
 **/
public class ResponseFuture<T> {

    private CountDownLatch countDownLatch = new CountDownLatch(1);

    private T result;

    private boolean success;

    private Throwable cause;

    private SendCallback sendCallback;

    private Class responseClazz;

    private RemotingRequestType requestType;

    public ResponseFuture() {
    }

    public ResponseFuture(SendCallback sendCallback) {
        this.sendCallback = sendCallback;
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public SendCallback getSendCallback() {
        return sendCallback;
    }

    public void setSendCallback(SendCallback sendCallback) {
        this.sendCallback = sendCallback;
    }

    public Throwable getCause() {
        return cause;
    }

    public void setCause(Throwable cause) {
        this.cause = cause;
    }

    public Class getResponseClazz() {
        return responseClazz;
    }

    public void setResponseClazz(Class responseClazz) {
        this.responseClazz = responseClazz;
    }

    public RemotingRequestType getRequestType() {
        return requestType;
    }

    public void setRequestType(RemotingRequestType requestType) {
        this.requestType = requestType;
    }

    public T get() throws InterruptedException {
        countDownLatch.await();
        return result;
    }

    public T get(long timeoutMillis) throws InterruptedException {
        countDownLatch.await(timeoutMillis, TimeUnit.MILLISECONDS);
        return result;
    }

    public void put(T t) {
        result = t;
    }

    public void rouse() {
        countDownLatch.countDown();
    }

    public void putAndRouse(T t) {
        put(t);
        rouse();
    }
}
